/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package person.notification;

import java.io.Serializable;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import system.general.Exc;
import system.general.Logged;
import system.general.Message;
import system.general.Persistencia;

/**
 *
 * @author gilberto
 */
@ManagedBean(name = "person_notification")
@RequestScoped
public class Main extends Beans implements Serializable {
    //Variables de importación General

    Logged logged;
    private Persistencia persistencia = new Persistencia();
    private Message msg = new Message();
    //Variables de importación otros modulos
    //Variables del modulo
    private Find person_notificationFind = new Find();
    private List<Beans> person_notificationList = new ArrayList<>();
    //Variables locales
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private String sql;
    private Map<String, String> map = new LinkedHashMap<>();
    private person.message.Main person_messageMain = new person.message.Main();

    public Main() {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        logged = (Logged) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "logged");
    }

    private void load() {
        try {
            //Verifica si hay un registro seleccionado
            if (logged.getMasterId() == 0) {
                return;
            }

            map.clear();
            map.put("sm.id = " + logged.getDetailId(), " ");

            person_notificationList.clear();
            person_notificationList = person_notificationFind.byMap(map);

            setId_emisor(person_notificationList.get(0).getId_emisor());
            setMensaje(person_notificationList.get(0).getMensaje());
            setFecha(person_notificationList.get(0).getFecha());
            getPersonBeans().setNombre(person_notificationList.get(0).getPersonBeans().getNombre());
            getPersonBeans().setApellido(person_notificationList.get(0).getPersonBeans().getApellido());

            sql = "UPDATE public.persona_mensaje SET "
                    + "estatus = 'true' WHERE "
                    + "id_mensaje = " + logged.getDetailId()
                    + " AND id_receptor = " + logged.getLoggedId();

            persistencia.executeUpdate(sql);
        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void insert() {
        try {

            setId_emisor(logged.getLoggedId());

            sql = "INSERT INTO public.sistema_mensaje (id_emisor, mensaje, fecha) "
                    + "VALUES ("
                    + getId_emisor() + ", "
                    + "'" + getMensaje() + "', "
                    + "CURRENT_TIMESTAMP)";

            //Inserta la información del usuario
            persistencia.executeUpdate(sql);

            map.put("sm.id_emisor = " + getId_emisor(), " AND ");
            map.put("sm.mensaje = '" + getMensaje() + "'", " ");
            person_notificationList = person_notificationFind.byMap(map);

            logged.setTempId(person_notificationList.get(0).getId());

            person_messageMain.insert();

            clearBeans();

            throw new Exc("m1");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public Integer messages() {
        try {
            map.clear();
            map.put("pm.id_receptor = " + logged.getLoggedId(), " AND ");
            map.put("pm.estatus = false", " ");

            person_notificationList.clear();
            person_notificationList = person_notificationFind.byMap(map);
        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
        if (!person_notificationList.isEmpty()) {
            return person_notificationList.size();
        } else {
            return 0;
        }
    }

    public List<Beans> list_messages() {
        try {
            map.clear();
            map.put("pm.id_receptor = " + logged.getLoggedId(), " ");

            person_notificationList.clear();
            person_notificationList = person_notificationFind.byMap(map);
            if (!person_notificationList.isEmpty()) {
                setId_emisor(person_notificationList.get(0).getId_emisor());
                setMensaje(person_notificationList.get(0).getMensaje());
                setFecha(person_notificationList.get(0).getFecha());
            }
        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
        return person_notificationList;
    }

    public void update() {
        try {

            //Verifica si hay registros seleccionados
            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }


        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void delete() {
        try {

            //Verifica si hay registros seleccionados
            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }

            //Elimina el resgistro por el id_persona
            deleteById(logged.getMasterId());
            clear();

            throw new Exc("m3");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void deleteById(int id) throws Exc, SQLException, Exception {

        //Verifica si el usuario ya existe para otra persona
        sql = "DELETE FROM public.persona_mensaje "
                + "WHERE id_mensaje = " + id
                + " AND id_receptor = " + logged.getLoggedId();

        persistencia.executeUpdate(sql);
    }

    public void clear() {
        logged.setMasterId(0);
        clearBeans();
        map.clear();
    }

    public void selectedRecordId(int recordId) {
        logged.setDetailId(recordId);
        load();
    }

    private String namePackage() {
        Package pack = this.getClass().getPackage();
        return pack.getName();
    }
}
